package com.kd.juhaowan.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.kd.juhaowan.R;
import com.kd.juhaowan.http.model.VersionModel;
import com.kd.juhaowan.model.LoginUser;
import com.kd.juhaowan.utils.LogUtil;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class VersionUpdateActivity extends BaseActivity {



    @BindView(R.id.update_version)
    TextView versionView;
    @BindView(R.id.update_content)
    TextView contentView;
    private VersionModel versionModel;

    @BindView(R.id.login_confirm)
    TextView downLoadText;

    @BindView(R.id.update_close)
    LinearLayout closeLayout;
    @BindView(R.id.progress_layout)
    RelativeLayout progressLayout;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.progress_text)
    TextView progressText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        versionModel = (VersionModel)getIntent().getSerializableExtra("model");
        versionView.setText("v"+versionModel.getNewversion());
        contentView.setText(versionModel.getContent());
        closeLayout.setVisibility(0==versionModel.getEnforce()? View.VISIBLE:View.INVISIBLE);

    }

    @Override
    protected void reInitDate() {

    }
    private File loadFile;

    public void startVersionInstallTask() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        final Uri apkUri;

        if (loadFile == null && !loadFile.exists()) {
            LogUtil.debugLog("gamedetal", "startVersionInstallTask ========> file is not exists");
            return;
        }

        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String authority = getApplication().getPackageName() + ".PhotoPicker";
            apkUri = FileProvider.getUriForFile(getApplicationContext(), authority, loadFile);
//            apkUri = Uri.fromFile(file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            apkUri = Uri.fromFile(loadFile);
        }

        LogUtil.debugLog("gamedetal", "startVersionInstallTask ========> apkUri: " + apkUri.toString());

        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        startActivity(intent);
    }

    private boolean isVisible = false;

    @Override
    protected void onResume() {
        super.onResume();
        isVisible = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isVisible = false;
    }

    private void startDownload(){
        downLoadText.setVisibility(View.GONE);
        progressLayout.setVisibility(View.VISIBLE);
        StringBuilder builder = new StringBuilder(versionModel.getNewversion())
                .append("lingyishouyou");
//        builder.append(gameid);
        builder.append(".apk");
        loadFile = new File(getExternalCacheDir(), builder.toString());
//        mSinglePath = FileDownloadUtils.getDefaultSaveRootPath()+
////                File.separator+"feifei_save"+
//                File.separator+model.getGame_package_name().trim()+".apk";;
//        mSinglePath = file.getAbsolutePath();

        BaseDownloadTask singleTask = FileDownloader.getImpl().create(versionModel.getDownloadfile())
//                .setPath(mSinglePath,false)
                .setPath(loadFile.getAbsolutePath(),false)
                .setCallbackProgressTimes(300)
                .setMinIntervalUpdateSpeed(400)
                //.setTag()
                .setListener(new FileDownloadSampleListener(){
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei","pending taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes);

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
//                        downloadView.setText("下载中（"+(int)(soFarBytes*1.0/totalBytes*100)+"%）");
                        if(isVisible){
                            int progre = (int)(soFarBytes*1.0/totalBytes*100);
                            progressBar.setProgress(progre);
                            progressText.setText(progre+"%");
                        }
//                        downLoadText.setText("下载中（"++"%）");
                        Log.d("feifei","progress taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes+",speed:"+task.getSpeed());
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
//                        startVersionInstallTask(new File(mSinglePath));
//                        Intent intent = new Intent(MainActivity.this,VersionUpdateActivity.class);
//                        intent.putExtra("model",versionModel);
//                        updateLauncher.launch(intent);
                        if(isVisible){
                            progressBar.setProgress(100);
                            progressText.setText("100%");
//                            progressLayout.setVisibility(View.GONE);
//                            downLoadText.setVisibility(View.VISIBLE);
                        }

                        startVersionInstallTask();
                        Log.d("feifei","blockComplete taskId:"+task.getId()+",filePath:"+task.getPath()+",fileName:"+task.getFilename()+",speed:"+task.getSpeed()+",isReuse:"+task.reuse());
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        Log.d("feifei","completed taskId:"+task.getId()+",isReuse:"+task.reuse());
//                        startVersionInstallTask(new File(mSinglePath));
                        if(isVisible){
                            progressBar.setProgress(100);
                            progressText.setText("100%");
//                            progressLayout.setVisibility(View.GONE);
//                            downLoadText.setVisibility(View.VISIBLE);
                        }

                        startVersionInstallTask();

                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei","paused taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes);
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Log.d("feifei","error taskId:"+task.getId()+",e:"+e.getLocalizedMessage());
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        Log.d("feifei","warn taskId:"+task.getId());
                    }
                });

        singleTaskId =  singleTask.start();

    }
    private int singleTaskId;

    LoginUser myuser =null;

    @OnClick({R.id.login_confirm,R.id.progress_layout})
    public void onConfirmClick(){
//        setResult(RESULT_OK);
//        finish();
        startDownload();
    }
    @OnClick(R.id.update_close)
    public void onCancelClick(){
        if(0==versionModel.getEnforce()){
            setResult(RESULT_CANCELED);
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        onCancelClick();
    }

    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.activity_version_update;
    }




}
